<template>
  <div class="container clearfix">
    <div class="wrapper">
      <div class="cinema-wrapper">
        <div class="btn-wrapper">
        </div>
        <div class="seat-wrapper">
          <div class="illustration">
            <div class="illustration-img-wrapper unselected-seat"></div>
            <span class="illustration-text">可选</span>
            <div class="illustration-img-wrapper selected-seat"></div>
            <span class="illustration-text">已选</span>
            <div class="illustration-img-wrapper bought-seat"></div>
            <span class="illustration-text">不可选</span>
          </div>
          <div class="inner-seat-wrapper" ref="innerSeatWrapper">
            <div class="screen">3号激光厅银幕</div>
            <div class="screen-center">
              银幕中央
              <div class="mid-line"></div>
            </div>
            <div v-for="row in seatRow" :key="row">
              <!--这里的v-if很重要，如果没有则会导致报错，因为seatArray初始状态为空-->
              <div
                v-for="col in seatCol"
                v-if="seatArray.length > 0"
                class="seat"
                :style="{ width: seatSize + 'px', height: seatSize + 'px' }"
                :key="col"
              >
                <div
                  class="inner-seat"
                  @click="handleChooseSeat(row - 1, col - 1)"
                  v-if="seatArray[row - 1][col - 1] !== -1"
                  :class="{
                    'unselected-seat': seatArray[row - 1][col - 1] === 1,
                    'selected-seat': seatArray[row - 1][col - 1] === 3,
                    'bought-seat': seatArray[row - 1][col - 1] === 2 || seatArray[row - 1][col - 1] === 9
                  }"
                >{{seatArray[row - 1][col - 1]}}</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="modal-container" style="" v-if="CanSelected">
      <div class="modal">
        <span class="icon"></span>

        <p class="tip">一次最多购买{{ maxSelectedNum }}张票</p>

        <div class="ok-btn btn" @click="CanSelected = false">我知道了</div>
      </div>
    </div>
    <side-vue :selectedList="selectedList" :total="totalPrice" :price="price" :pId="parseInt(pId)" :maxSelectedNum="maxSelectedNum"></side-vue>
  </div>
</template>

<script>
import { mapState, mapGetters } from 'vuex'
import sideVue from './Side.vue'
import { getTicketsByPId } from '@/api/ticket'
export default {
  name: 'cinemaSeatChoose',
  components: {
    sideVue
  },
  data () {
    return {
      // 影院座位的二维数组,-1为非座位，0为未购座位，1为已选座位(绿色),2为已购座位(红色)
      // 影院座位行数
      // 座位尺寸
      seatList: [],
      seatSize: 30,
      selectedList: [],
      CanSelected: false,
      totalPrice: 0,
      seatArray: [],
    }
  },
  computed: {
    ...mapState('ticket', ['plan']),
    mId () {
      return this.$route.query.mId
    },
    pId () {
      return this.$route.query.pId
    },
    seatRow () {
      let result = 0
      for (let i = 0; i < this.seatList.length; i++) {
        if (this.seatList[i].seatRow > result) {
          result = this.seatList[i].seatRow
        }
      }
      return result
    },
    seatCol () {
      let result = 0
      for (let i = 0; i < this.seatList.length; i++) {
        if (this.seatList[i].seatColumn > result) {
          result = this.seatList[i].seatColumn
        }
      }
      return result
    },
    price () {
      return this.plan.price
    },
    maxSelectedNum () {
      return this.plan.hMax
    }
  },
  methods: {
    getSeatArray () {
      const result = []
      for (let i = 0; i < this.seatList.length; i++) {
        const row = this.seatList[i].seatRow
        const col = this.seatList[i].seatColumn
        if (result[row - 1] === undefined) {
          result[row - 1] = []
        }
        result[row - 1][col - 1] = this.seatList[i].ticketStatus
      }
      return result
    },

    // 重置座位
    resetSeat: function () {
      // 将所有座位的值变为0
      const oldArray = this.seatArray.slice()
      for (let i = 0; i < this.seatRow; i++) {
        for (let j = 0; j < this.seatCol; j++) {
          if (oldArray[i][j] !== -1) {
            oldArray[i][j] = 1
          }
        }
      }
      this.seatArray = oldArray
      this.selectedList = []
      this.totalPrice = 0
    },
    // 选定且购买座位
    buySeat: function () {
      // 遍历seatArray，将值为1的座位变为2
      const oldArray = this.seatArray.slice()
      for (let i = 0; i < this.seatRow; i++) {
        for (let j = 0; j < this.seatCol; j++) {
          if (oldArray[i][j] === 3) {
            oldArray[i][j] = 2
          }
        }
      }
      this.seatArray = oldArray
    },
    // 处理座位选择逻辑
    handleChooseSeat: function (row, col) {
      const seatValue = this.seatArray[row][col]
      const newArray = this.seatArray
      // 如果是已购座位，直接返回
      if (seatValue === 2 || seatValue === 9) return
      // 如果是已选座位点击后变未选并将从已选座位中移除
      if (seatValue === 3) {
        newArray[row][col] = 1
        const json = {
          row: row + 1,
          col: col + 1
        }
        // 将与该json相同的元素从数组中移除
        this.selectedList = this.selectedList.filter((item) => {
          return item.row !== json.row || item.col !== json.col
        })
        this.$store.dispatch('ticket/setSelectedList', this.selectedList)
        this.totalPrice = this.selectedList.length * this.price
      }
      // 如果是未选座位点击后变已并将添加进已选座位
      if (seatValue === 1) {
        if (this.selectedList.length >= this.maxSelectedNum) {
          this.CanSelected = true
          return
        }
        newArray[row][col] = 3
        const json = {
          row: row + 1,
          col: col + 1
        }
        this.selectedList.push(json)
        this.$store.dispatch('ticket/setSelectedList', this.selectedList)
        this.totalPrice = this.selectedList.length * this.price
      }
      // 必须整体更新二维数组，Vue无法检测到数组某一项更新,必须slice复制一个数组才行
      this.seatArray = newArray.slice()
    },
    // 初始座位数组
    initSeatArray: function () {
      this.seatSize = this.$refs.innerSeatWrapper
        ? parseInt(
          parseInt(
            window.getComputedStyle(this.$refs.innerSeatWrapper).width,
            10
          ) / this.seatCol,
          10
        )
        : 0
    }
  },

  mounted: async function () {
    this.$store.dispatch('ticket/getPlanByPId', this.pId)
    const data = await getTicketsByPId(this.pId)
    console.log(data)
    this.seatList = data.data
    this.seatArray = this.getSeatArray()
    this.initSeatArray()
    this.$bus.$on('buy', (flag) => {
      if (flag) {
        this.buySeat()
      }
    })
    this.$bus.$on('unLockTicket', (flag) => {
      if (flag) {
        this.resetSeat()
      }
    })
  },
  beforeDestroy: function () {
    this.$bus.$off('buy')
    this.$bus.$off('unLockTicket')
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.container {
  width: 1300px;
  margin: 0 auto;
}

.clearfix:after,
.clearfix:before {
  content: " ";
  display: table;
}

.wrapper {
  width: 820px;
  padding: 40px;
  display: inline-block;
  box-sizing: border-box;
  vertical-align: top;
}

.cinema-wrapper {
  font-size: 0;
  overflow: auto;
  margin-left: 20px;
  white-space: nowrap;
}

.title {
  text-align: center;
}

.seat-wrapper {
  height: 700px;
  width: 1000px;
  border: 1px dotted #c5c5c5;
  margin: 0 auto;
  position: relative;
  overflow: auto;
}

.screen {
  margin: 0 auto;
  height: 30px;
  width: 300px;
  background-color: #e3e3e3;
  border-radius: 0 0 30px 30px;
  color: #585858;
  line-height: 30px;
  text-align: center;
}

.inner-seat-wrapper {
  margin-left: 50px;
  position: relative;
  padding-top: 112px;
  overflow: auto;
}

.seat {
  float: left;
  display: flex;
  justify-content: center;
  align-items: center;
}

.inner-seat {
  width: 80%;
  height: 80%;
  cursor: pointer;
}

.selected-seat {
  background: url("@/assets/selected.png") center center no-repeat;
  background-size: 100% 100%;
}

.unselected-seat {
  background: url("@/assets/unselected.png") center center no-repeat;
  background-size: 100% 100%;
}

.bought-seat {
  background: url("@/assets/bought.png") center center no-repeat;
  background-size: 100% 100%;
}

.screen-center {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  padding: 5px;
  font-size: 13px;
  border-radius: 5px;
  top: 50px;
  background-color: #f6f6f6;
  color: #636363;
  border: 1px solid #b1b1b1;
}

.mid-line {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  top: 100%;
  width: 1px;
  height: 800px;
  border-left: 1px dashed #919191;
}

.btn-wrapper {
  margin: 20px auto;
  width: 1000px;
  height: 30px;
  text-align: center;
}

.btn-buy {
  height: 100%;
  line-height: 30px;
  font-size: 14px;
  border-radius: 5px;
  padding: 0 5px;
  background-color: #ffa349;
  color: #ffffff;
  display: inline-block;
  cursor: pointer;
  margin-right: 10px;
}

.smart {
  background-color: #39ac6a;
}

.illustration {
  position: absolute;
  left: 0;
  top: 0;
  height: 35px;
  width: 300px;
}

.illustration-img-wrapper {
  width: 25px;
  height: 25px;
  position: relative;
  top: 50%;
  display: inline-block;
  transform: translateY(-50%);
  margin-left: 10px;
}

.illustration-text {
  display: inline-block;
  height: 100%;
  line-height: 35px;
  font-size: 14px;
  position: relative;
  top: -2px;
}
.modal-container {
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  z-index: 1000;
  background-color: rgba(0, 0, 0, 0.4);
}
.modal-container .modal {
  width: 460px;
  height: 155px;
  padding: 30px 0;
  position: absolute;
  margin: auto;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  background-color: #fff;
  text-align: center;
}
.modal-container .icon {
  display: inline-block;
  width: 50px;
  height: 50px;
  background: url()
    no-repeat;
}
.modal-container .tip {
  font-size: 14px;
  color: #666;
  margin-bottom: 26px;
  margin-top: 12px;
}
.modal-container .ok-btn {
  color: #fff;
  background-color: #f03d37;
  -webkit-box-shadow: 0 2px 10px -2px #f03d37;
  box-shadow: 0 2px 10px -2px #f03d37;
}

.modal-container .btn {
  border-radius: 100px;
  height: 42px;
  line-height: 42px;
  font-size: 16px;
  width: 260px;
  padding: 0;
  cursor: default;
}
.btn {
  display: inline-block;
  padding: 2px 15px;
  line-height: 25px;
  font-size: 15px;
  color: #fff;
  background-color: #df2d2d;
}
</style>
